package tp1POO.Persistencia;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnitUtil;
import tp1POO.Modelo.ObjetoPOO;

/**
 * Implementacao de DAO para o banco de dados
 * @author alan
 */
public class DAOBD implements DAO{

	/**
	 * Construtor padrao
	 */
	public DAOBD() {
		emf = Persistence.createEntityManagerFactory("locarrao");
		em = emf.createEntityManager();
		util = emf.getPersistenceUnitUtil();
	}

	/**
	 * Salva objeto no banco de dados
	 * @param parObj objeto a ser persistido
	 */
	@Override
	public void salvar(ObjetoPOO parObj) {
		try {
			if(parObj != null) {
				transaction = em.getTransaction();
				transaction.begin();
				//Object parObjID = util.getIdentifier(parObj);
                                em.merge(parObj);
				transaction.commit();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Apaga objeto do banco de dados
	 * @param parObj objeto a ser apagado
	 */
	@Override
	public void apagar(ObjetoPOO parObj) {
		try {
			if(parObj != null) {
				transaction = em.getTransaction();
				transaction.begin();
				Object parObjID = util.getIdentifier(parObj);
				parObj = em.find(parObj.getClass(), parObjID);
				em.remove(parObj);
				transaction.commit();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 */
	@Override
	public ObjetoPOO encontrar(ObjetoPOO parObj) {
		ObjetoPOO retorno = null;
		try {
			if(parObj != null) {
				transaction = em.getTransaction();
				transaction.begin();
				Object parObjID = util.getIdentifier(parObj);
				retorno = em.find(parObj.getClass(), parObjID);
				transaction.commit();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return retorno;
	}

	@Override
	public ObjetoPOO converterObj(String parString) {
		return null;
	}

	@Override
	public List<ObjetoPOO> listar(ObjetoPOO parObj) {
		try {
			if(parObj != null) {
				transaction = em.getTransaction();
				transaction.begin();
				List<ObjetoPOO> results = em.createQuery("from " + parObj.getClass().getName()).getResultList();
				transaction.commit();
				return results;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private EntityTransaction transaction;
	private EntityManagerFactory emf;
	private EntityManager em;
	private PersistenceUnitUtil util;
}
